﻿using FluentNHibernate;
using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Diagnostics;
using NHibernate.Cfg;
using NHibernate.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;

namespace AspNetDemo.App_Start
{
    public class HibernateConfig
    {
        public static Configuration BuildConfig()
        {
            var configuration = Fluently.Configure()
                .Database(GetPersistenceConfigurer())
                .Mappings(m => m.AutoMappings.Add(AutoMap.Source(new TypeSource())))
                .BuildConfiguration()
                .AddProperties(new Dictionary<string, string>
                {
                    { NHibernate.Cfg.Environment.ShowSql, Boolean.TrueString},
                    { NHibernate.Cfg.Environment.FormatSql, Boolean.TrueString }
                });

            return configuration;
        }

        private static IPersistenceConfigurer GetPersistenceConfigurer()
        {
            return MsSqlConfiguration.MsSql2012
                .ConnectionString(x => x.FromConnectionStringWithKey("connectionString"))
                .IsolationLevel(System.Data.IsolationLevel.ReadCommitted)
                ;
        }
    }

    public class TypeSource : ITypeSource
    {
        public string GetIdentifier()
        {
            throw new NotImplementedException();
        }

        public IEnumerable<Type> GetTypes()
        {
            return Assembly.GetExecutingAssembly().GetTypes().Where(x => !x.IsAbstract && x.IsClass && x.IsPublic && x.Namespace.Contains(".Models"));
        }

        public void LogSource(IDiagnosticLogger logger)
        {
            throw new NotImplementedException();
        }
    }
}